<template>
	<view class="">
		<wd-tabs v-model="tab" swipeable auto-line-width @change="handleChange">

			<block v-for="item in tabs" :key="item.value">
				<wd-tab :title="`${item.label}`" :name="item.value">
					<view class="px-1 py-1">
						<wd-message-box />
						<wd-toast />
						<wd-search v-model="value" @search="search" hide-cancel placeholder-left placeholder="请输入关键字">
							<template #prefix>
								<wd-popover mode="menu" :content="menu" @menuclick="changeSearchType">
									<view class="search-type">
										<text>{{ searchType }}</text>
										<wd-icon custom-class="icon-arrow" name="fill-arrow-down"></wd-icon>
									</view>
								</wd-popover>
							</template>
						</wd-search>

						<wd-table :data="list" :height="600" :border="false" @row-click="handleClick">
							<!-- 表格列定义 -->
							<wd-table-col v-for="(col, index) in columns" :key="index" :prop="col.prop"
								:label="col.label" :width="col.width || '60'" :align="col.align || 'center'">
								<template #value="{ row }">
									<template v-if="col.isTag">
										<wd-tag custom-class="space"
											:type="col.color ? col.color(row[col.prop]) : 'primary'">
											{{ col.format ? (col.format(row[col.prop]) || '-') : (row[col.prop] || '-')
											}}
										</wd-tag>
									</template>
									<template v-else>
										{{ row[col.prop] || '-' }}
									</template>
								</template>
							</wd-table-col>
							<wd-table-col prop="grade" label="操作" width="200" fixed align="left">
								<template #value="{ row }">
									<text class="px-1 text-#4d80f0" @click.stop="handleProcessDetail(row)">
										查看
									</text>
									<text class="px-1 text-#4d80f0" v-if="row.status === 3"
										@click.stop="row.status === 3  ? handleAddOrEdit(row.id, true) : handleAddOrEdit(row.id)">
										{{ row.status === 0 ? '修改' :  row.status === 3 ? '重新填写' : ''
										}}
									</text>
									<text class="px-1 text-#4d80f0" @click.stop="handleDelete(row.id)">
										{{ row.status === 0 ? '取消' : '' }}
									</text>
									<text class="px-1 text-#4d80f0" @click.stop="handleExpedite(row)">
										{{ row.status !== 2 && row.status !== 4 ? '催办' : '' }}
									</text>
								</template>
							</wd-table-col>
						</wd-table>

						<!-- 分页组件 -->
						<Pagination :total="total" :pageNo="queryParams.pageNo" :pageSize="queryParams.pageSize"
							@update:pageNo="changePage" />
						<view class="mx-12 my-8 ">
							<up-button text="新增" color="#5ac725" shape="circle" @click="handleAddOrEdit()"></up-button>
						</view>


					</view>
				</wd-tab>
			</block>

		</wd-tabs>
	</view>
</template>

<script setup lang="ts">
import { onShow } from '@dcloudio/uni-app'
import { ref, onMounted } from 'vue'
import { DICT_TYPE, getIntDictOptions, getDictLabel, getDictColor } from '@/utils/dict'
import Pagination from '@/components/pagination/index.vue'
import { useMessage, useToast } from 'wot-design-uni'
import * as VehicleInCity from '@/api/oa/vehicleout/inCity'
import * as VehicleOutCity from '@/api/oa/vehicleout/outCity'
import { expediting } from '@/utils/processinstance'


const message = useMessage()
const toast = useToast()

const tab = ref('InCity')
const tabs = ref([
	{
		label: '市内',
		value: 'InCity'
	},
	{
		label: '市外',
		value: 'OutsideCity'
	},
])
// 确保列配置的 prop 唯一性
const columns = [
	{ prop: 'driverName', label: '驾驶员姓名', width: 160 },
	// { prop: 'driverPhonenumber', label: '联系电话', width: 110 },
	// { prop: 'userId', label: '用车人', width: 100 },
	// { prop: 'userPhone', label: '用车人电话', width: 120 },
	// { prop: 'deptName', label: '用车部门' },
	// { prop: 'sortOrder', label: '编号', align: 'center' },
	// { prop: 'carType', label: '车型' },
	// { prop: 'drivingRoute', label: '行驶路线', width: 160 },
	// { prop: 'drivingKilometer', label: '行驶公里数' },
	// { prop: 'startTime', label: '开始日期', width: 160 },
	// { prop: 'endTime', label: '结束日期', width: 160 },
	// { prop: 'cost', label: '费用' },
	// { prop: 'driverRemark', label: '备注' },
	{
		prop: 'status',
		label: '审批状态',
		align: 'center',
		width: 80,
		format: (val: any) => getDictLabel(DICT_TYPE.BPM_TASK_STATUS, val),
		color: (val: any) => getDictColor(DICT_TYPE.BPM_TASK_STATUS, val),
		isTag: true
	}
] as any
// 响应式数据
const list = ref<VehicleInCity.VehicLeOutVO[]>([])
const queryParams = ref<any>({
	pageNo: 1,
	pageSize: 10,
	type: 1,
	driverName: undefined,
	driverPhonenumber: undefined,

})
const total = ref(0)
const loading = ref(false)

const searchType = ref<string>('驾驶员姓名')
const value = ref<string>('')
const menu = ref<any[]>([
	{
		content: '驾驶员姓名',
		prop: 'driverName'
	},
	// {
	// 	content: '驾驶人联系电话',
	// 	prop: 'driverPhonenumber'
	// }
])

const handleChange = (value: any) => {
	if (value.name === 'InCity') {
		queryParams.value.type = 1
		fetchList()
	}
	if (value.name === 'OutsideCity') {
		queryParams.value.type = 2
		fetchList()
	}
}
function changeSearchType({ item }: { item: any }) {
	searchType.value = item?.content
}
const search = () => {
	// 找到选中的搜索字段
	const selectedMenu = menu.value.find(item => item.content === searchType.value);
	if (selectedMenu) {
		// 清空之前的搜索条件
		queryParams.value.driverName = undefined;
		queryParams.value.driverPhonenumber = undefined;
		// 根据选中的搜索类型设置搜索值
		queryParams.value[selectedMenu.prop] = value.value.trim();
		// 重新获取数据
		fetchList();
	}
};

const getDict = (type: any, value: any) => {
	const dicts = getIntDictOptions(type)
	const dict = dicts.find(item => item.value === value)
	return dict ? dict.label : '待审批'
}
// 切换分页
const changePage = (newPage: any) => {
	queryParams.value.pageNo = newPage
	fetchList()
}
// 获取车辆外派列表
const fetchList = async () => {
	loading.value = true
	try {
		const api = tab.value === 'InCity' ? VehicleInCity.getVehicLeOutPage : VehicleOutCity.getVehicLeOutPage
		const response = await api(queryParams.value)
		list.value = response.list
		total.value = response.total
		for (let item of list.value) {
			item.status = item.isApproved === false ? 0 : item.status;
		}
	} catch (error) {
		console.error(error)
	} finally {
		loading.value = false
	}
}
/** 审批进度 */
const handleProcessDetail = (row: any) => {
	const url = tab.value === 'InCity' ? `/pagesPackage/OAsystemAutomation/vehicleoutsourcing/1-dayDispatch/detail?processInstanceId=${row.processInstanceId}&id=${row.id}`
		: `/pagesPackage/OAsystemAutomation/vehicleoutsourcing/Over1-dayDispatch/detail?processInstanceId=${row.processInstanceId}&id=${row.id}`
	uni.navigateTo({
		url: url
	});
}
/** 点击一整行跳转至详情页面 */
const handleClick = ({ rowIndex }: any) => {
	handleProcessDetail(list.value[rowIndex])

}
/** 新增页面 */
const handleAddOrEdit = (id?: any, resubmit = false) => {
	let url = tab.value === 'InCity' ? `/pagesPackage/OAsystemAutomation/vehicleoutsourcing/1-dayDispatch/create`
		: `/pagesPackage/OAsystemAutomation/vehicleoutsourcing/Over1-dayDispatch/create`
	// 如果 id 存在，拼接 id 作为参数
	if (id) {
		if (resubmit === true) {
			console.log('resubmit', resubmit);
			url += `?id=${id}&resubmit=1`;
		}
		console.log('传过来的Id', id);
		url += `?id=${id}&resubmit=0`;
	} else {
		url += `?resubmit=0`;
	}
	uni.navigateTo({ url });
}
/** 删除按钮操作 */
const handleDelete = async (id: number) => {
	try {
		// 删除的二次确认
		await message.confirm({
			msg: '您确定要取消吗？',
			title: '提示'  // 添加标题
		})
		// 发起删除
		const api = tab.value === 'InCity' ? VehicleInCity.deleteVehicLeOut : VehicleOutCity.deleteVehicLeOut
		await api(id)
		// 显示成功提示
		toast.success('取消成功')
		// 刷新列表
		await fetchList()
	} catch (error) {
		console.log('用户取消了操作或发生错误:', error)
	}
}
const handleExpedite = (row: any) => {
	expediting({
		processInstanceId: row.processInstanceId,
		processName: '青运-办公系统自动化-车辆外派'
	})
}
// 生命周期
onMounted(() => {
	fetchList()
})
onShow(() => {
	fetchList()
})
</script>

<style scoped lang="scss"></style>